package com.xiaocai.myblog.services;

import com.xiaocai.myblog.enums.ErrorCodeEnum;
import com.xiaocai.myblog.exception.BusinessException;
import com.xiaocai.myblog.utils.MailUtil;
import com.xiaocai.myblog.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chenhefu
 * @date 2019-09-30 22:06
 */
@Service
public class EmailService {

    @Autowired
    private RedisUtil redisUtil;

    public boolean sendCode(String email){
        int tempCode = (int) ((Math.random() * 9 + 1) * 100000);
        String code = String.valueOf(tempCode);
        String codeKey = "send_email_key_" + email;
        //设置邮箱验证码为3分钟
        boolean isSuccess = redisUtil.set(codeKey, code, 3*60*60);
        if (!isSuccess){
            throw new BusinessException(ErrorCodeEnum.SERVER_ERROR);
        }
        return MailUtil.sendEmail(email, code);
    }
}
